/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.partaljevic.tapestry.gambling.pages;


import com.partaljevic.gambling.Customer;
import com.partaljevic.gambling.beans.Team;
import com.partaljevic.gambling.beans.Match;
import com.partaljevic.gambling.beans.Pair;
import com.partaljevic.gambling.beans.Result;
import com.partaljevic.tapestry.gambling.service.Customers;
import com.partaljevic.tapestry.gambling.service.MatchesService;
import com.partaljevic.tapestry.gambling.service.PairsOfTickets;
import com.partaljevic.tapestry.gambling.service.ResultService;
import com.partaljevic.tapestry.gambling.service.TeamService;
import com.partaljevic.tapestry.gambling.service.TicketService;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Danilo
 */
public class Working {

@Inject
private MatchesService matchesService;
@Inject
private TeamService teamService;
@Inject
private ResultService resultService;
@Inject
private Customers customers;
@Inject
private TicketService tickets;
@Inject
private PairsOfTickets pairs;

    public void readList(InputStream is) throws Exception {

  try {

  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(is);
  doc.getDocumentElement().normalize();
  NodeList nodeLst = doc.getElementsByTagName("MATCH");

  for (int s = 0; s < nodeLst.getLength(); s++) {

      Match match = new Match();
    Node fstNode = nodeLst.item(s);

    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

           Element element = (Element) fstNode;
      NodeList homeElementList = element.getElementsByTagName("DOMACI");
      Element homeElement = (Element) homeElementList.item(0);
      NodeList home = homeElement.getChildNodes();
      match.setHome(((Node) home.item(0)).getNodeValue());
      if(!isExist(((Node) home.item(0)).getNodeValue())){
      teamService.save(new Team(((Node) home.item(0)).getNodeValue()));
      }

      NodeList awayElementList = element.getElementsByTagName("GOSTI");
      Element awayElement = (Element) awayElementList.item(0);
      NodeList away = awayElement.getChildNodes();
      match.setAway(((Node) away.item(0)).getNodeValue());
      if(!isExist(((Node) away.item(0)).getNodeValue())){
      teamService.save(new Team(((Node) away.item(0)).getNodeValue()));
      }

      NodeList startElementList = element.getElementsByTagName("POCETAK");
      Element startElement = (Element) startElementList.item(0);
      NodeList start = startElement.getChildNodes();
      match.setMatchStart(((Node) start.item(0)).getNodeValue());

      NodeList kecElementList = element.getElementsByTagName("KEC");
      Element kecElement = (Element) kecElementList.item(0);
      NodeList kec = kecElement.getChildNodes();
      match.setKec(Double.parseDouble(((Node) kec.item(0)).getNodeValue()));

      NodeList dvojkaElementList = element.getElementsByTagName("DVOJKA");
      Element dvojkaElement = (Element) dvojkaElementList.item(0);
      NodeList dvojka = dvojkaElement.getChildNodes();
      match.setDvojka(Double.parseDouble(((Node) dvojka.item(0)).getNodeValue()));

      NodeList iksElementList = element.getElementsByTagName("IKS");
      Element iksElement = (Element) iksElementList.item(0);
      NodeList iks = iksElement.getChildNodes();
      match.setIks(Double.parseDouble(((Node) iks.item(0)).getNodeValue()));
    }
    matchesService.save(match);
  }
  } catch (Exception e) {
      throw new Exception();
  }
 }
    private boolean isExist(String name){
        for (Team team : teamService.retreive()) {
            if(team.getName().equals(name)) return true;
        }
        return false;
    }

    public void readResult(InputStream is) throws Exception {

//        resultService.retreive().clear();

  try {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(is);
  doc.getDocumentElement().normalize();
  NodeList nodeLst = doc.getElementsByTagName("MATCH");

  for (int s = 0; s < nodeLst.getLength(); s++) {

    Result result = new Result();
    Node fstNode = nodeLst.item(s);

    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

           Element element = (Element) fstNode;
      NodeList homeElementList = element.getElementsByTagName("DOMACI");
      Element homeElement = (Element) homeElementList.item(0);
      NodeList home = homeElement.getChildNodes();
      result.setHome(((Node) home.item(0)).getNodeValue());

      NodeList awayElementList = element.getElementsByTagName("GOSTI");
      Element awayElement = (Element) awayElementList.item(0);
      NodeList away = awayElement.getChildNodes();
      result.setAway(((Node) away.item(0)).getNodeValue());

      NodeList rezElementList = element.getElementsByTagName("REZULTAT");
      Element rezElement = (Element) rezElementList.item(0);
      NodeList rez = rezElement.getChildNodes();
      result.setMatchResult(((Node) rez.item(0)).getNodeValue());
    }
    findTeam(result.getHome()).processingResult(result);
    findTeam(result.getAway()).processingResult(result);
    resultService.save(result);
    checkPairs(result);
  }
  } catch (Exception e) {
      throw new Exception();
  }
 }
    private Team findTeam(String name){
        for (Team team : teamService.retreive()) {
            if(team.getName().equals(name)){
                return team;
            }
        }
        return null;
    }

   public void checkTeams(Result r){
       for (Team team : teamService.retreive()) {
           if(team.getName().equalsIgnoreCase(r.getHome())||team.getName().equalsIgnoreCase(r.getAway())){
           team.processingResult(r);
           teamService.update(team);
           }
       }
   }

   public void checkPairs(Result r){
       for (Pair match : pairs.retreive()) {
           if(match.getHome().equalsIgnoreCase(r.getHome())&& match.getType().equalsIgnoreCase(checkResult(r))){
               match.setWinner(true);
               pairs.update(match);
           }
       }
   }

   public void checkTickets(){
       for (Customer customer : customers.retrieve()) {
           for (com.partaljevic.gambling.beans.Ticket ticket : customer.getWinner()) {
               if(!ticket.isPaid()){
                   ticket.setPaid(true);
                   customer.setScore(customer.getScore()+ticket.getGain());
                   customers.update(customer);
                   tickets.update(ticket);
               }
           }
       }
   }
    

    public String checkResult(Result result){
        String[] help = result.getMatchResult().split(":");
        if(Integer.parseInt(help[0])>Integer.parseInt(help[1])){
            return "1";
        }
        else if(Integer.parseInt(help[0])==Integer.parseInt(help[1])){
            return "X";
        }
        else{
            return "2";
        }
    }
}
